package controllers

import (
	"encoding/json"
	"github.com/beego/beego/v2/core/logs"
	"personal-skill/constants"
	"personal-skill/models"
	"personal-skill/util/redisutil"
	"personal-skill/util/resultutil"
)

type MenuController struct {
	BaseController
}

func (menuController *MenuController) Get() {

}

func (menuController *MenuController) Post() {

}

func (menuController *MenuController) Put() {

}

func (menuController *MenuController) Delete() {

}

func (menuController *MenuController) GetMenuTreeOfAll() {
	// 先从缓存中获取
	menuTreeJsonStr, err2 := redisutil.GetStr(constants.RedisKeyMenuTreeOfAll)
	menuTree := &models.MenuTreeItem{}
	if err2 == nil && menuTreeJsonStr != "" {
		err2 := json.Unmarshal([]byte(menuTreeJsonStr), menuTree)
		if err2 == nil {
			menuController.ResponseJson(resultutil.SuccessWithData(menuTree))
		} else {
			logs.Error("反序列化所有菜单数据失败", err2)
		}
	}
	// 从数据库获取
	menuTree, err := models.GetMenuTreeOfAll()
	if err != nil {
		logs.Error(err)
		menuController.ResponseJson(resultutil.Error(resultutil.MenuNotFoundErr))
	}
	marshal, err := json.Marshal(menuTree)
	menuTreeOfAllJson := string(marshal)
	err = refreshAllMenuCache(menuTreeOfAllJson)
	if err != nil {
		logs.Error("缓存所有菜单树数据出错", err)
	}
	menuController.ResponseJson(resultutil.SuccessWithData(menuTree))
}

// GetDefaultMenuNo 获取用户默认权限
func (menuController *MenuController) GetDefaultMenuNo() {
	// 先从缓存中获取
	str, err := redisutil.GetStr(constants.RedisKeyMenuTreeOfDefault)
	var defaultMenuNo []string
	if err == nil && str != "" {
		err := json.Unmarshal([]byte(str), &defaultMenuNo)
		if err == nil {
			menuController.ResponseJson(resultutil.SuccessWithData(defaultMenuNo))
		}
	}
	// 缓存中没有则从数据库获取
	defaultMenuNo = models.GetDefaultMenuNo()
	marshal, err := json.Marshal(defaultMenuNo)
	if err == nil {
		err := refreshDefaultMenuCache(string(marshal))
		if err != nil {
			logs.Error("缓存默认菜单权限到redis出错", err)
		}
	}
	menuController.ResponseJson(resultutil.SuccessWithData(defaultMenuNo))
}

// 刷新缓存中的所有菜单
func refreshAllMenuCache(newMenu string) error {
	return redisutil.SetStr(constants.RedisKeyMenuTreeOfAll, newMenu, constants.DefaultCacheTime)
}

// 刷新缓存中的所有菜单
func refreshDefaultMenuCache(newMenu string) error {
	return redisutil.SetStr(constants.RedisKeyMenuTreeOfDefault, newMenu, constants.DefaultCacheTime)
}
